#include "StdAfx.h"

BOOL AdjustProcessPrivileges(LPCSTR szPrivilegesName)   
{   
    HANDLE hToken;    
    TOKEN_PRIVILEGES tkp;   
    
    if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))   
    {   
       return FALSE;   
    }   
    
    if(!LookupPrivilegeValue(NULL, szPrivilegesName, &tkp.Privileges[0].Luid))   
    {   
        CloseHandle(hToken);   
        return FALSE;   
    }   
       
    tkp.PrivilegeCount = 1;   
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;   
        
    if(!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL))   
    {   
        CloseHandle(hToken);   
        return 0;   
    }   
        
    CloseHandle(hToken);   
    return TRUE;   
}

ui32 StartupHandler::CheckProcesses()
{
	if(!AdjustProcessPrivileges(SE_DEBUG_NAME))
		return 1;

	DWORD dwNeeded;

	DWORD lpdwProcs[65535];
	BOOL fSuc = EnumProcesses(lpdwProcs, 65535 * 4, &dwNeeded);
	if(fSuc == FALSE)
		return 1;

	DWORD numProcesses = dwNeeded / 4;
	
	for(ui32 i = 0; i < numProcesses; ++i)
	{
		HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, lpdwProcs[i]);
		if(hProcess == NULL || hProcess == INVALID_HANDLE_VALUE)
			continue;

		HMODULE hBaseModule;
		fSuc = EnumProcessModules(hProcess, &hBaseModule, sizeof(hBaseModule), &dwNeeded);
		if(fSuc == FALSE || dwNeeded < sizeof(hBaseModule))
		{
			CloseHandle(hProcess);
			continue;
		}

		if(GetCurrentProcessId() == lpdwProcs[i])
		{
			CloseHandle(hProcess);
			continue;
		}
	}

	return 0;
}